// pages/recipe/edit.js
const { get, put, post, upload } = require('../../utils/request')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        recipeId: null,
        name: '',
        description: '',
        image: '',
        ingredients: '',
        steps: '',
        cookingTime: '',
        difficulty: '简单',
        category: '',
        nutrition: {
            calories: '',
            protein: '',
            carbs: '',
            fat: '',
            fiber: ''
        },
        tags: '',
        difficulties: ['简单', '中等', '困难'],
        isFormValid: false,
        isEdit: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.id) {
            this.setData({ 
                recipeId: options.id,
                isEdit: true
            })
            this.loadRecipeData(options.id)
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async loadRecipeData(recipeId) {
        try {
            wx.showLoading({
                title: '加载中'
            })

            const res = await get(`/recipes/${recipeId}`)
            const recipe = res

            this.setData({
                name: recipe.name,
                description: recipe.description || '',
                image: recipe.image || '',
                ingredients: Array.isArray(recipe.ingredients) ? recipe.ingredients.join('\n') : recipe.ingredients || '',
                steps: Array.isArray(recipe.steps) ? recipe.steps.join('\n') : recipe.steps || '',
                cookingTime: recipe.cookingTime || '',
                difficulty: recipe.difficulty || '简单',
                category: recipe.category || '',
                nutrition: {
                    calories: recipe.nutrition?.calories || '',
                    protein: recipe.nutrition?.protein || '',
                    carbs: recipe.nutrition?.carbs || '',
                    fat: recipe.nutrition?.fat || '',
                    fiber: recipe.nutrition?.fiber || ''
                },
                tags: Array.isArray(recipe.tags) ? recipe.tags.join(',') : recipe.tags || ''
            })

            this.checkFormValid()
        } catch (error) {
            console.error('加载菜谱数据失败:', error)
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            })
        } finally {
            wx.hideLoading()
        }
    },

    onNameInput(e) {
        this.setData({
            name: e.detail.value
        })
        this.checkFormValid()
    },

    onDescriptionInput(e) {
        this.setData({
            description: e.detail.value
        })
    },

    onIngredientsInput(e) {
        this.setData({
            ingredients: e.detail.value
        })
        this.checkFormValid()
    },

    onStepsInput(e) {
        this.setData({
            steps: e.detail.value
        })
        this.checkFormValid()
    },

    onCookingTimeInput(e) {
        this.setData({
            cookingTime: e.detail.value
        })
    },

    onDifficultyChange(e) {
        this.setData({
            difficulty: this.data.difficulties[e.detail.value]
        })
    },

    onCategoryInput(e) {
        this.setData({
            category: e.detail.value
        })
    },

    onCaloriesInput(e) {
        this.setData({
            'nutrition.calories': e.detail.value
        })
    },

    onProteinInput(e) {
        this.setData({
            'nutrition.protein': e.detail.value
        })
    },

    onCarbsInput(e) {
        this.setData({
            'nutrition.carbs': e.detail.value
        })
    },

    onFatInput(e) {
        this.setData({
            'nutrition.fat': e.detail.value
        })
    },

    onFiberInput(e) {
        this.setData({
            'nutrition.fiber': e.detail.value
        })
    },

    onTagsInput(e) {
        this.setData({
            tags: e.detail.value
        })
    },

    async chooseImage() {
        try {
            const res = await wx.chooseMedia({
                count: 1,
                mediaType: ['image'],
                sizeType: ['compressed']
            })

            wx.showLoading({
                title: '上传中'
            })

            const tempFilePath = res.tempFiles[0].tempFilePath
            console.log('开始上传图片:', tempFilePath)
            
            const imageUrl = await this.uploadImage(tempFilePath)
            console.log('上传成功，返回URL:', imageUrl)

            this.setData({
                image: imageUrl
            })

            wx.hideLoading()
        } catch (error) {
            console.error('选择或上传图片失败:', error)
            wx.showToast({
                title: '选择图片失败',
                icon: 'none'
            })
        }
    },

    async uploadImage(tempFilePath) {
        try {
            console.log('调用上传接口')
            const res = await upload('/upload/image', tempFilePath)
            console.log('上传接口返回:', res)
            return res.url
        } catch (error) {
            console.error('上传接口错误:', error)
            throw new Error('上传图片失败')
        }
    },

    checkFormValid() {
        const { name, ingredients, steps } = this.data
        const isFormValid = name.trim() && ingredients.trim() && steps.trim()
        this.setData({ isFormValid })
    },

    async handleSubmit() {
        if (!this.data.isFormValid) {
            return
        }

        try {
            wx.showLoading({
                title: '保存中'
            })

            const recipeData = {
                name: this.data.name,
                description: this.data.description,
                image: this.data.image,
                ingredients: this.data.ingredients.split('\n').filter(item => item.trim()),
                steps: this.data.steps.split('\n').filter(item => item.trim()),
                cookingTime: parseInt(this.data.cookingTime) || 0,
                difficulty: this.data.difficulty,
                category: this.data.category,
                nutrition: this.data.nutrition,
                tags: this.data.tags.split(',').map(tag => tag.trim()).filter(Boolean)
            }

            let res
            if (this.data.isEdit) {
                res = await put(`/recipes/${this.data.recipeId}`, recipeData)
            } else {
                res = await post('/recipes', recipeData)
            }

            if (res) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success'
                })
                
                // 返回上一页并刷新
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                if (prevPage && prevPage.loadRecipes) {
                    prevPage.loadRecipes()
                }
                
                setTimeout(() => {
                    wx.navigateBack()
                }, 1500)
            } else {
                throw new Error(res.message)
            }
        } catch (error) {
            console.error('保存菜谱失败:', error)
            wx.showToast({
                title: error.message || '保存失败',
                icon: 'none'
            })
        } finally {
            wx.hideLoading()
        }
    }
})